package cn.jdy.plugins.wap;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.common.util.ScoreRuleUtil;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.safe.SafeUtil;
import cn.jdy.payment.entity.Orders;
import cn.jdy.payment.service.OrderService;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Business;
import cn.jdy.plugins.entity.Collect;
import cn.jdy.plugins.entity.Discuss;
import cn.jdy.plugins.entity.Doc;
import cn.jdy.plugins.entity.Download;
import cn.jdy.plugins.entity.Info;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.BusinessService;
import cn.jdy.plugins.service.CollectService;
import cn.jdy.plugins.service.DiscussService;
import cn.jdy.plugins.service.DocService;
import cn.jdy.plugins.service.DownloadService;
import cn.jdy.plugins.service.InfoService;

/**
 * 我的商机汇
 *
 * @author zhaigt
 */
@Controller
@RequestMapping("/member")
public class MemberCtrl extends BaseCtrl {
	@Autowired
	private CollectService collectService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private BusinessService businessService;
	@Autowired
	private ConfService confService;
	@Autowired
	private DiscussService discussService;
	@Autowired
	private InfoService infoService;
	@Autowired
	private DocService docService;
  @Autowired
  private DownloadService downloadService;

	/**
	 * 会员 个人中心 首页
	 *
	 * @author: wuzhiliang
	 * @date: 2013-10-15 16:53
	 */
	@RequestMapping("")
	public ModelAndView index(Orders order) {
		ModelAndView mv = new ModelAndView(super.t + "/member/member");
		try {
		  mv.addObject("menus", getMenus());//菜单
			// 用户信息 手机号中间替换为*
			Member member = super.getMember(true);
 
	    /* 等级计算 等级类型分2种3级 */
			Integer score = member.getScore();
			if(score==null) score = 0;
			int createrlevel = ScoreRuleUtil.getlevel(score);
			mv.addObject("createrlevel", String.valueOf(createrlevel));
			mv.addObject("member", member);

			// 我的消息记录数 用与首页 气泡显示
			mv.addObject("infoCount", infoService.count("userid",member.getId()));

		} catch(Exception e) {
			mv.addObject("msg", "error");
			BaseLog.e(this.getClass(), "updResetPwd:会员 资料管理有误", e);
		}
		return mv;
	}

	/**
	 * 个人中心的菜单列表配置
	 * @return
	 */
	private List<ConfValue> getMenus() {
    String path = request.getContextPath();
    List<ConfValue> menus = new LinkedList<ConfValue>();

    ConfValue cv0 = new ConfValue();
    cv0.setValue0("我的消息");
    cv0.setValue1(path+"/member/myinfo");
    cv0.setValue2("/static/img/myxx.png");
    cv0.setRemark("#d87570");

    ConfValue cv1 = new ConfValue();
    cv1.setValue0("我的收藏");
    cv1.setValue1(path+"/member/mycollect");
    cv1.setValue2("/static/img/mysc.png");
    cv1.setRemark("#d87570");

    ConfValue cv2 = new ConfValue();
    cv2.setValue0("我的下载");
    cv2.setValue1(path+"/member/myorders");
    cv2.setValue2("/static/img/myorder.png");
    cv2.setRemark("#118adb");

    ConfValue cv3 = new ConfValue();
    cv3.setValue0("上传文章");
    cv3.setValue1(path+"/member/mydoc");
    cv3.setValue2("/static/img/mywz.png");
    cv3.setRemark("#58d2f0");

    ConfValue cv4 = new ConfValue();
    cv4.setValue0("下载文章");
    cv4.setValue1(path+"/member/mydown");
    cv4.setValue2("/static/img/mydwon.png");
    cv4.setRemark("#febf02");

    ConfValue cv5 = new ConfValue();
    cv5.setValue0("我的贡献");
    cv5.setValue1(path+"/member/mygongxian");
    cv5.setValue2("/static/img/mygx.png");
    cv5.setRemark("#bc4040");

    ConfValue cv6 = new ConfValue();
    cv6.setValue0("上传信息");
    cv6.setValue1(path+"/business/initHeJameng");
    cv6.setValue2("/static/img/myup.png");
    cv6.setRemark("#ff8b00");

    ConfValue cv8 = new ConfValue();
    cv8.setValue0("修改密码");
    cv8.setValue1(path+"/member/updatePwd");
    cv8.setValue2("/static/img/mypwd.png");
    cv8.setRemark("#58d2f0");

    menus.add(cv0);
    menus.add(cv1);
    menus.add(cv3);
    menus.add(cv4);
    menus.add(cv2);
    menus.add(cv5);
    menus.add(cv6);
    menus.add(cv8);
    return menus;
  }

	@RequestMapping("/{forward}")
	public ModelAndView updatePwd(@PathVariable("forward")  String forward){
		ModelAndView mv = new ModelAndView(super.t + "/member/"+forward);
		Member member = super.getMember(true);
		mv.addObject("member", member);
		return mv;
	}

	/**
	 * 会员管理手机号重置
	 *
	 * @param mobile
	 * @param userid
	 * @return
	 */
	@RequestMapping("/forUpdateMobile")
	public ModelAndView forUpdateMobile(String mobile, String userid) {
		ModelAndView mv = new ModelAndView(super.t + "/login");
		try {
			Member mbo = new Member();
			mbo.setMobile(mobile);
			mbo.setId(userid);
			memberService.updateMobile(mbo);

			Member memberBo = (Member) super.getMember();
			memberBo.setMobile(mobile);
			
			// 密码修改成功 跳转到 登录页面并提示
      mv.addObject("msg", "密码修改成功!");//
		} catch(BaseException e) {
			mv.addObject("msg", "error");
			BaseLog.e(this.getClass(), "updResetPwd:会员管理手机号重置有误", e);
		}
		return mv;
	}

	/**
	 * 会员管理用手机号重置密码
	 *
	 * @return
	 */
	@RequestMapping("/forUpdatePwd")
	public ModelAndView forUpdatePwd(String password) {
		ModelAndView mv = new ModelAndView("redirect:/login?errorType=10");
		try {
			Member mbo = new Member();
			Member memberBo = super.getMember();
			mbo.setId(memberBo.getId());
			mbo.setPassword(SafeUtil.md5(password).substring(8, 16));
			memberService.updResetPwd(mbo);
			session.invalidate();
		} catch(BaseException e) {
			BaseLog.e(this.getClass(), "updResetPwd:密码修改有误", e);
		}
		return mv;
	}


	/**
   * 查询我的收藏
   */
  @RequestMapping("/mycollect")
  public ModelAndView mycollect(Collect collect, String fromDate, String toDate) {
    ModelAndView mv = new ModelAndView(super.t+"/member/mycollect");
//    try {
//      //设置分页信息
//      if(collect.getiDisplayLength() == 0) collect.setiDisplayLength(5);                //默认长度5
//      if(collect.getPageNo()<=0) collect.setPageNo(1);                                  //默认页数1
//      collect.setiDisplayStart((collect.getPageNo() - 1) * collect.getiDisplayLength());  //显示起始索引
//
//      mv.addAllObjects(collectService.query(collect, super.getMember().getId(), fromDate, toDate));
//      mv.addObject("pageNo", collect.getPageNo());
//      mv.addObject("fromDate", fromDate);
//      mv.addObject("toDate", toDate);
//    } catch(Exception e) {
//      BaseLog.e(this.getClass(), "查询我的收藏信息错误", e);
//    }
    return mv;
  }
	/**
   * 查询我的收藏
   */
  @RequestMapping("/mycollectLoadMore")
  @ResponseBody
  public Map<String, Object> mycollectLoadMore(Collect collect, String fromDate, String toDate) {
    Map<String, Object> resp = new HashMap<>();
    try {
      //设置分页信息
      if(collect.getiDisplayLength() == 0) collect.setiDisplayLength(5);                //默认长度5
      if(collect.getPageNo()<=0) collect.setPageNo(1);                                  //默认页数1
      collect.setiDisplayStart((collect.getPageNo() - 1) * collect.getiDisplayLength());  //显示起始索引

      List list = (List)collectService.query(collect, super.getMember().getId(), fromDate, toDate).get("dataList");
      if(list!=null && list.size()>0) {
        resp.put("dataList", list);
        resp.put("statusCode", 200);
      }else {
        resp.put("statusCode", 400);
      }
    } catch(Exception e) {
      BaseLog.e(this.getClass(), "查询我的收藏信息错误", e);
    }
    return resp;
  }

	/**
	 * 我的贡献信息
	 *
	 * @param business
	 * @return
	 */
	@RequestMapping("/mygongxian")
	public ModelAndView mygongxian(Business business) {
		ModelAndView mv = new ModelAndView(super.t+"/member/mygongxian");
//		try {
//			if(business.getiDisplayLength() == 0) business.setiDisplayLength(5);                //默认长度5
//			if(business.getPageNo()<=0) business.setPageNo(1);                                  //默认页数1
//			business.setiDisplayStart((business.getPageNo() - 1) * business.getiDisplayLength());  //显示起始索引
//
//			business.setCreater(getMember().getId());
//
//			mv.addObject("dataList", businessService.query(business));
//			mv.addObject("total", businessService.count(business));
//			mv.addObject("pageNo", business.getPageNo());
//			mv.addObject("size", business.getiDisplayLength());
//		} catch(Exception e) {
//			BaseLog.e(this.getClass(), "查询我的贡献信息错误", e);
//		}
		return mv;
	}
	/**
	 * 我的贡献信息
	 *
	 * @param business
	 * @return
	 */
	@RequestMapping("/mygongxianLoadMore")
    @ResponseBody
	public Map<String, Object> mygongxianLoadMore(Business business) {
      Map<String, Object> resp = new HashMap<>();
		try {
			if(business.getiDisplayLength() == 0) business.setiDisplayLength(5);                //默认长度5
			if(business.getPageNo()<=0) business.setPageNo(1);                                  //默认页数1
			business.setiDisplayStart((business.getPageNo() - 1) * business.getiDisplayLength());  //显示起始索引
			business.setCreater(getMember().getId());

          List list = businessService.query(business);
          if(list!=null && list.size()>0) {
            resp.put("dataList", list);
            resp.put("statusCode", 200);
          }else {
            resp.put("statusCode", 400);
          }
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询我的贡献信息错误", e);
		}
		return resp;
	}

	/**
   * 我的消息信息
   *
   * @param bo
   * @param pageSize
   * @return
   */
  @RequestMapping("/myinfo")
  public ModelAndView forMyMessage(Info bo, Integer pageSize,String searchtype) {
    ModelAndView mv = new ModelAndView(super.t+"/member/myinfo");
    return mv;
  }
  
  /**
   * 我的消息信息
   *
   * @param bo
   * @param pageSize
   * @return
   */
  @RequestMapping("/myinfoLoadMore")
  @ResponseBody
  public Map<String, Object> myinfoLoadMore(Info bo, Integer pageSize,String searchtype) {
      Map<String, Object> resp = new HashMap<>();
      
    bo.setUserid(super.getMember().getId());
    if(!"-1".equals(searchtype)){// -1 全部
      bo.setFlag(searchtype);
    }
    try {
      /************* 分页处理开始 ************/
      String Count = infoService.getInfoCount(bo);//查询我的消息信息总条数
      Map<String, Integer> map = getPageInfo(bo.getPageNo(), pageSize, Count);//获取page信息
      bo.setPageNo(map.get("currentPage"));
      pageSize = map.get("pageSize");
      /************* 分页处理结束 ***********/

      bo.setPagestart((bo.getPageNo() - 1) * pageSize);//查询起始值
      bo.setPagesize(pageSize);//查询条数
      List<Info> list = infoService.query(bo);

      for(Info info:list){
        if(info.getType().equals("4")){//前台用户
          Member member = memberService.find(info.getSendUserId());
          if(member!=null)
            info.setSendUsername(member.getUserName());
        }else if(info.getType().equals("2")){
//          User user =  userManage.findOne("id", info.getSendUserId());
//          if(user!=null)
//            info.setSendUsername(user.getUsername());
        }else{
          info.setSendUsername("system");
        }
      }

        if(list!=null && list.size()>0) {
            resp.put("dataList", list);
            resp.put("statusCode", 200);
        }else {
            resp.put("statusCode", 400);
        }
//      mv.addObject("menberBo", (Member) super.getMember());
    } catch(Exception e) {
      BaseLog.e(this.getClass(), "查询我的消息信息错误", e);
    }
    return resp;
  }

  /**
   * 根据id 查看消息信息
   * @param id
   * @return
   */
  @RequestMapping("/myinfo/{id}")
  public ModelAndView findInfoById(@PathVariable String id){
      ModelAndView mv = new ModelAndView(super.t + "/member/myinfoDetail");
      try{
          if(null!=id && !"".equals(id)){
              Info info = infoService.find(id);
              mv.addObject("infobo",info);
              if(info!=null){
                  info.setFlag("1");
                  infoService.update(info);
              }
          }
      }catch (Exception e){
          BaseLog.e(this.getClass(),"查找消息失败！",e);
      }
      return mv;
  }
  
  /**
   * 我的文章：智库列表
   * @param entity
   * @return
   */
  @RequestMapping("/mydoc")
  public ModelAndView mydoc(Doc entity) {
    ModelAndView mv = new ModelAndView(super.t+"/member/mydoc");
//    try {
//      //设置分页信息
//        if(entity.getPageNo()==0) entity.setPageNo(1);
//        if(entity.getiDisplayLength()==0) entity.setiDisplayLength(5);
//        entity.setiDisplayStart((entity.getPageNo()-1)*entity.getiDisplayLength());
//
//        entity.setUserId(getMember(false).getId());
//        List list = docService.query(entity);
//      mv.addObject("dataList", docService.query(entity));
//
//      Filter filter = new Filter();
//      filter.addCondition("userId", getMember().getId());
//      mv.addObject("doctotal", docService.count(filter));
//
//      mv.addObject("pageNo", entity.getPageNo());
//      mv.addObject("size", entity.getiDisplayLength());
//      mv.addObject("entity", entity);
//
//    } catch(Exception e) {
//      BaseLog.e(this.getClass(), "list", e);
//    }
    return mv;
  }
    /**
     * 我的文章：智库列表
     * @param entity
     * @return
     */
    @RequestMapping("/mydocLoadMore")
    @ResponseBody
    public Map<String, Object> mydocLoadMore(Doc entity) {
        Map<String, Object> resp = new HashMap<>();
        try {
            if(entity.getPageNo()==0) entity.setPageNo(1);
            if(entity.getiDisplayLength()==0) entity.setiDisplayLength(5);
            entity.setiDisplayStart((entity.getPageNo()-1)*entity.getiDisplayLength());

            entity.setUserId(getMember(false).getId());
            List list = docService.query(entity);
            if(list!=null && list.size()>0) {
                resp.put("dataList", list);
                resp.put("statusCode", 200);
            }else {
                resp.put("statusCode", 400);
            }
        } catch(Exception e) {
            BaseLog.e(this.getClass(), "list", e);
        }
        return resp;
    }

  /**
   * 查询我的下载
   * @param download
   * @return
   */
  @RequestMapping("/mydown")
  public ModelAndView mydown(Download download, String fromDate, String toDate) {
    ModelAndView mv = new ModelAndView(super.t+"/member/mydown");
//
//    try {
//      if(download.getPageNo()==0) download.setPageNo(1);
//      if(download.getiDisplayLength()==0) download.setiDisplayLength(5);
//      download.setiDisplayStart((download.getPageNo()-1)*download.getiDisplayLength());
//
//        download.setUserId(getMember(false).getId());
//
//      mv.addObject("dataList", downloadService.queryWapList(download));
//      mv.addObject("total", downloadService.count(download));
//      mv.addObject("pageNo", download.getPageNo());
//      mv.addObject("size", download.getiDisplayLength());
//    } catch (Exception e) {
//      BaseLog.e(this.getClass(), "查询我的下载", e);
//    }

    return mv;
  }
  /**
   * 查询我的下载
   * @param download
   * @return
   */
  @RequestMapping("/mydownLoadMore")
  @ResponseBody
  public Map<String, Object> mydownLoadMore(Download download, String fromDate, String toDate) {
    Map<String, Object> resp = new HashMap<>();
    try {
      if(download.getPageNo()==0) download.setPageNo(1);
      if(download.getiDisplayLength()==0) download.setiDisplayLength(5);
      download.setiDisplayStart((download.getPageNo()-1)*download.getiDisplayLength());

        download.setUserId(getMember(false).getId());
      List list = downloadService.queryWapList(download);
      if(list!=null && list.size()>0) {
        resp.put("dataList", list);
        resp.put("statusCode", 200);
      }else {
        resp.put("statusCode", 400);
      }
    } catch (Exception e) {
      BaseLog.e(this.getClass(), "查询我的下载", e);
    }

    return resp;
  }

  /**
   * 我的订单
   */
  @RequestMapping("/myorders")
  public ModelAndView queryOrders(Orders order, String fromDate, String toDate) {
    ModelAndView mv = new ModelAndView(super.t + "/member/myorders");
    return mv;
  }
  /**
   * 我的订单
   */
  @RequestMapping("/myordersLoadMore")
  @ResponseBody
  public Map<String, Object> myordersLoadMore(Orders order, String fromDate, String toDate) {
    Map<String, Object> resp = new HashMap<>();
    try {
      //设置分页信息
      if(order.getiDisplayLength() == 0) order.setiDisplayLength(5);                //默认长度5
      if(order.getPageNo()<=0) order.setPageNo(1);                                  //默认页数1
      order.setiDisplayStart((order.getPageNo() - 1) * order.getiDisplayLength());  //显示起始索引

      order.setUserId(getMember(false).getId());
      List list = orderService.queryOrders(order, fromDate, toDate);
      if(list!=null && list.size()>0) {
        resp.put("dataList", list);
        resp.put("statusCode", 200);
      }else{
        resp.put("statusCode", 400);
      }
    } catch(Exception e) {
      BaseLog.e(this.getClass(), "queryOrders", e);
    }
    return resp;
  }

	/**
	 * 查看我的贡献消息详情 查询评论
	 * @param discuss
	 * @return
	 */
	@RequestMapping("/queryDis")
	@ResponseBody
	public List<Discuss> queryDis(Discuss discuss) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			return discussService.find("businessId", discuss.getBusinessId());
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(this.getClass(), "查询评论错误", e);
		}
		return null;
	}

	/**
	 * @param bo
	 * @return
	 * @title : 上传我的加盟信息
	 * @description: 跳转到上传我的加盟信息页面
	 */
	@RequestMapping("/forMyupsjfile")
	public ModelAndView forMyupsjfile(Business bo) {
		ModelAndView mv = new ModelAndView("/my/myupsjfile.jsp");
		try {
			List<ConfValue> businessclassList = confService.queryByType(GlobalConstant.TYPE_BUSINESS, 0L);// 商分类
			// 8
			// 放常量
			mv.addObject("classList", businessclassList);
			// 预计加盟时间
      Date date1 = new Date();
      mv.addObject("addYear", date1.getYear()+1900);// 当前年份
      mv.addObject("addMonth", date1.getMonth()+1);// 当前月份
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "跳转到上传我的加盟信息页面错误", e);
		}
		return mv;
	}

	@RequestMapping("/checkPwd")
	@ResponseBody
	public Map<String, Object> checkPwd(String param) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Member member = super.getMember();
		if(param!=null && member!=null && SafeUtil.md5(param).substring(8, 16).equals(member.getPassword())) {
			jsonMap.put("status", "y");
		} else {
			jsonMap.put("status", "n");
			jsonMap.put("info", "原密码错误");
		}
		return jsonMap;
	}
	
	/**
	 * wap会员个人中心
	 * @param mb
	 * @return
	 */
	@RequestMapping("/vipCenter")
	public ModelAndView vip4wap(Member user){
		ModelAndView mv = new ModelAndView("/my/my.jsp");
		return mv;
	}
	
	/**
	 * wap会员个人资料
	 * @param user
	 * @return
	 */
	@RequestMapping("/personalInfo")
	public ModelAndView pinfo4wap(Member user){
		ModelAndView mv = new ModelAndView("/my/myInfo.jsp");
		return mv;
	}
}
